import time
from ..comm.comm import TComm
import  json

class TSvrData:
    def __init__(self):
        self.dictDevs ={}
        self.dictVars ={}
        self.values ={}
        self.dbConnection=None
        self.tdbHost = "hh.hhdata.cn"
        self.tdbPort= 31299
        self.tdbToken= "Basic cm9vdDpoaHVjMTExNQ=="
        self.tdbDB= "pcs2024"
        self.tdbToken= "Basic cm9vdDpoaHVjMTExNQ=="
    def load(self):
        try:
            sqls="select * from v_dict_dev; select * from v_dict_var  order by regAddr;"
            rs = self.dbConnection.query(sqls)
            devs = rs[0]
            vars = rs[1]
            for d in devs:
                dev ={
                    "vars": {}
                }
                for k,v in d.items():
                    dev[k] = v
                self.dictDevs[dev['devCode']] = dev
            for dp in vars:
                var={}
                for k,v in dp.items():
                    var[k] = v
                varId = var['varId']
                devCode = var['devCode']
                if devCode in self.dictDevs.keys():
                    self.dictDevs[devCode]['vars'][varId] = var
                self.dictVars[varId] = var
                self.values[varId]={
                    'ov':0,
                    'nv':0,
                    'tm':0
                }
            print('load server data (devices , datapoints).')
        except Exception as er:
            print(er)
    def getDicts(self):
        res = {}
        try:
            res = self.dictDevs
        except Exception as er:
            print(er)
        return  res
    def getDevValues(self , devCode):
        res ={}
        try:
            if devCode in  self.dictDevs.keys():
                dev = self.dictDevs[devCode]
                for k,v in dev['vars'].items():
                    if k in  self.values.keys():
                        res[k] = self.values[k]['nv']
        except Exception as er:
            print(er)
        return  res
    def getFullValues(self):
        res ={}
        try:
            for k , v in self.values.items():
                res[k] = v['nv']
        except Exception as er:
            print(er)
        return  res
    def setValues(self , varValues):
        try:
            tm = time.time()
            for k ,v in varValues.items():
                if k in self.values.keys():
                    item = self.values[k]
                    item['ov'] = item['nv']
                    item['nv'] = v
                    item['tm'] = tm
                else:
                    self.values[k] = {
                        'ov': 0 ,
                        'nv': v,
                        'tm': tm
                    }
        except Exception as er:
            print(er)
    def queryHisDp(self , devCode , varName , fromDt , toDt):
        res = {}
        try:
            sql = "select * from dpvalues where d='"+devCode+"' and  k='"+varName+"' and time>='"+fromDt+"' and time<='"+toDt+"' order by time    limit 10000"
            resp = TComm.queryInfluxData(self.tdbHost , self.tdbPort , self.tdbDB , self.tdbToken , sql , "query")
            res = json.loads(resp.text)

        except Exception as er:
            print(er)
        return  res


    def apiPost(self , result , params , request):
        try:
            ps = {}
            tabName = ""
            dps =[]
            for k , v in params.items():
                if k in  self.values.keys():
                    ps[k]= v
                    arr = k.split("_")
                    dpStr = 'dpvalues,d='+arr[1]+',k='+"_".join(arr[2:])+' v='+str(v)
                    dps.append(dpStr)
            dpsStr = "\n".join(dps)
            self.setValues(ps)
            TComm.postInflux(self.tdbHost , self.tdbPort , self.tdbDB, self.tdbToken , dpsStr )

            result["result"]={
                "status": 1
            }
        except Exception as er:
            print(er)
    def apiGetFullVars(self , result , params , request):
        try:
            result["result"]={
                "status": 1,
                "action":"fullvars",
                "vars": self.getFullValues()
            }
        except Exception as er:
            print(er)
    def apiGetDevVars(self , result , params , request):
        try:
            if 'devCode' in params.keys():
                devCode = params['devCode']
                if devCode in self.dictDevs.keys():
                    result["result"]={
                        "status": 1,
                        "action":"fullvars",
                        "vars": self.getDevValues(devCode)
                    }
                else :
                    result["error"]['code'] = -1
                    result["error"]['message'] = "devCode is error."
            else :
                result["error"]['code'] = -2
                result["error"]['message'] = "devCode is None."
        except Exception as er:
            print(er)
    def apiGetDict(self , result , params , request):
        try:
            result["result"]={
                "status": 1,
                "action":"Dict",
                "vars": self.dictDevs
            }
        except Exception as er:
            print(er)
    def apiHisDp(self , result , params , request):
        try:
            if ('devCode' in params.keys()) and ('varName' in params.keys()) and  ('fromDt' in params.keys()) and ('toDt' in params.keys()):
                devCode = params['devCode']
                varName = params['varName']
                fromDt = params['fromDt']
                toDt = params['toDt']
                res = self.queryHisDp(devCode , varName , fromDt , toDt)
                result["result"]={
                    "status": 1,
                    "action":"queryHisDp",
                    "result": res
                }
            else :
                result["error"]['code'] = -2
                result["error"]['message'] = "devCode/varName/fromDt/toDt is None."
        except Exception as er:
            print(er)

svrData = TSvrData()
